package ysq.xyg.util;

import jxl.write.Label;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Execl工具类
 *
 * @author ysq
 * @create 2018-05-14 9:35
 **/
public class ImportExcelUtil {
    private static Logger log= LoggerFactory.getLogger(ImportExcelUtil.class);

    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel

    /**
     * 描述：获取IO流中的数据，组装成List<List<Object>>对象
     * @param in,fileName
     * @return
     * @throws IOException
     */
    public  List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception{
        List<List<Object>> list = null;
        //创建Excel工作薄
        Workbook work = this.getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}
            //遍历当前sheet中的所有行
            int n=sheet.getLastRowNum();
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if(row==null||row.getFirstCellNum()==j){continue;}

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    li.add(this.getCellValue(cell));
                }
                list.add(li);
            }
        }
        work.close();
        return list;
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003L.equals(fileType)){
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     * @param cell
     * @return
     */
    public  Object getCellValue(Cell cell){
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字

        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if("General".equals(cell.getCellStyle().getDataFormatString())){
                    //value = df.format(cell.getNumericCellValue());
                    Double z=cell.getNumericCellValue();
                    long longVal = Math.round(z);
                    Double t=Double.parseDouble(longVal + ".0");
                    if ( t.equals(z)){
                        value = longVal;
                    }else{
                        value=z;
                    }
                }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
                    value = sdf.format(cell.getDateCellValue());
                }else{
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }
    /**
     * 导出无表头excel 文件单个工作表(sheet)
     *
     * @param fileName
     * @param titleList
     * @param list
     * @param response
     */
    public static void exportNoHeadExcel(String fileName, String[] titleList,
                                         List list, HttpServletResponse response) {
        SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMdd");
        String todayStr = df.format(new Date());
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            String localFileName = fileName;
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
            fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            response.setContentType("application/vnd.ms-excel;");
            response.setHeader("Content-disposition", "attachment; filename=\""
                    + fileName + "_" + todayStr + ".xls\"");
            // 开始写入excel
            // 字段字体
            jxl.write.WritableFont wfc1 = new jxl.write.WritableFont(
                    WritableFont.COURIER, 10, WritableFont.NO_BOLD, true);
            jxl.write.WritableCellFormat wcfFC1 = new jxl.write.WritableCellFormat(
                    wfc1);
            wcfFC1.setAlignment(jxl.format.Alignment.CENTRE);
            wcfFC1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            // 结果字体
            jxl.write.WritableCellFormat wcfFC2 = new jxl.write.WritableCellFormat();
            wcfFC2.setAlignment(jxl.format.Alignment.CENTRE);
            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            WritableWorkbook wbook = jxl.Workbook.createWorkbook(os);
            // 写sheet名称
            WritableSheet wsheet = wbook.createSheet(localFileName, 0);
            for (int m = 0; m < titleList.length; m++) {
                wsheet.setColumnView(m, 30);
            }
            // 加入字段名
            for (int n = 0; n < titleList.length; n++) {
                wsheet.addCell(new jxl.write.Label(n, 0, titleList[n], wcfFC1));
            }
            // 写入流中
            int row = 0;
            for (int r = 0; r < list.size(); r++) {
                Object[] obj = (Object[]) list.get(r);
                for (int x = 0; x < titleList.length; x++) {
                    wsheet.addCell(new jxl.write.Label(x, row + 1,
                            obj[x] == null ? " " : obj[x].toString(), wcfFC1));
                }
                row++;
                if (row % 60000 == 0) {
                    row = 0;
                    // 写sheet名称
                    wsheet = wbook.createSheet(localFileName, 0);
                    for (int m = 0; m < titleList.length; m++) {
                        wsheet.setColumnView(m, 30);
                    }
                    // 加入字段名
                    for (int n = 0; n < titleList.length; n++) {
                        wsheet.addCell(new jxl.write.Label(n, 0, titleList[n],
                                wcfFC1));
                    }
                }
            }
            wbook.write();
            wbook.close();
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os == null) {
                log.info("os is null");
            } else {
                try {
                    os.close();
                    os = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导出excel 文件  带标题
     *
     * @param fileName
     * @param titleList
     * @param list
     * @param response
     */
    public static void exportWithHeadExcel(String fileName, String[] titleList,
                                           List list, HttpServletResponse response) {
        Date now = new Date();
        SimpleDateFormat dateformat = new java.text.SimpleDateFormat(
                "yyyy年MM月dd日HH时mm分");
        SimpleDateFormat df = new java.text.SimpleDateFormat("yyyyMMdd");
        String todayStr = df.format(new Date());
        String today = dateformat.format(now);
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            String localFileName = fileName;
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
            fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            response.setContentType("application/vnd.ms-excel;");
            response.setHeader("Content-disposition", "attachment; filename=\""
                    + fileName + "_" + todayStr + ".xls\"");
            // 开始写入excel
            // 加标题
            // 标题字体
            jxl.write.WritableFont wfc = new jxl.write.WritableFont(
                    WritableFont.COURIER, 18, WritableFont.NO_BOLD, false);
            jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(
                    wfc);
            wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
            wcfFC.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            // 字段字体
            jxl.write.WritableFont wfc1 = new jxl.write.WritableFont(
                    WritableFont.COURIER, 10, WritableFont.NO_BOLD, false);
            jxl.write.WritableCellFormat wcfFC1 = new jxl.write.WritableCellFormat(
                    wfc1);
            wcfFC1.setAlignment(jxl.format.Alignment.CENTRE);
            wcfFC1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            // 结果字体
            jxl.write.WritableCellFormat wcfFC2 = new jxl.write.WritableCellFormat();
            wcfFC2.setAlignment(jxl.format.Alignment.CENTRE);
            wcfFC2.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            WritableWorkbook wbook = jxl.Workbook.createWorkbook(os);
            // 写sheet名称
            WritableSheet wsheet = wbook.createSheet(localFileName, 0);
            int i = 3;
            for (int m = 0; m < titleList.length; m++) {
                wsheet.setColumnView(m, 30);
            }
            // 加入字段名
            for (int n = 0; n < titleList.length; n++) {
                wsheet.addCell(new jxl.write.Label(n, 3, titleList[n], wcfFC1));
            }
            // 加入标题
            wsheet.mergeCells(0, 0, i - 1, 0);
            wsheet.addCell(new Label(0, 0, localFileName, wcfFC));
            // 加入打印时间
            wsheet.addCell(new Label(i - 2, 1, "打印日期:"));
            wsheet.addCell(new Label(i - 1, 1, today));
            // 写入流中
            int row = 0;
            for (int r = 0; r < list.size(); r++) {
                Object[] obj = (Object[]) list.get(r);
                for (int x = 0; x < titleList.length; x++) {
                    wsheet.addCell(new jxl.write.Label(x, row + 4,
                            obj[x] == null ? " " : obj[x].toString(), wcfFC1));
                }
                row++;
                if (row % 60000 == 0) {
                    row = 0;
                    // 写sheet名称
                    wsheet = wbook.createSheet(localFileName, 0);
                    i = 3;
                    for (int m = 0; m < titleList.length; m++) {
                        wsheet.setColumnView(m, 30);
                    }
                    // 加入字段名
                    for (int n = 0; n < titleList.length; n++) {
                        wsheet.addCell(new jxl.write.Label(n, 3, titleList[n],
                                wcfFC1));
                    }
                    // 加入标题
                    wsheet.mergeCells(0, 0, i - 1, 0);
                    wsheet.addCell(new Label(0, 0, localFileName, wcfFC));
                    // 加入打印时间
                    wsheet.addCell(new Label(i - 2, 1, "打印日期:"));
                    wsheet.addCell(new Label(i - 1, 1, today));
                }
            }
            wbook.write();
            wbook.close();
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os == null) {
                log.info("os is null");
            } else {
                try {
                    os.close();
                    os = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
